#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "depot.h"

void init_depot(int n) {
	d = malloc( sizeof *d );
	d->s = INIT_SIZE;
	d->n = 0;
	d->tab = malloc( d->s* sizeof *(d->tab) );
	d->lgt = malloc( n * sizeof (int) );
	return;
}
int is_full() {
	if(d->n == d->s)
		return 1;
	else
		return 0;
}

void realloc_depot( void ) {
	if(is_full()) {
		d->s *= 2;
		d->tab = realloc( d->tab, d->s * sizeof * (d->tab) );
		return;
	} else
		return;
}	
void add_word( int elem ) {
	realloc_depot();
	d->tab[d->n] = elem;
	(d->n)++;
}
void add_lgt( int i ,int lgt ) {
	d->lgt[i] = lgt;
}

void sort_depot_lgt( int n ) {

	int i, j;
	int temp_lgt;
	int *temp_mem = malloc(32);
	for( i = 0; i < n; i++ ) {
		for( j = 0; j < n; j++ ) {
			if( d->lgt[j] > d->lgt[i] ) {
				memcpy( temp_mem, d->tab+i, d->lgt[i] * sizeof(int) );
				memcpy( d->tab+i, d->tab+j, d->lgt[j] * sizeof(int) );
				memcpy( d->tab+j, temp_mem, d->lgt[i] * sizeof(int) );
				temp_lgt = d->lgt[i];
				d->lgt[i] = d->lgt[j];
				d->lgt[j] = temp_lgt;
			} 
		}

	}
}

void sort_depot_num( int n ) {

	int i, j;
	int temp_lgt;
	int *temp_mem = malloc(32);
	for( i = 0; i < n; i++ ) {
		for( j = 0; j < n; j++ ) {
			if( d->lgt[j] == d->lgt[i] ) {
				if(cmp_str(d->tab+j, d->tab+i, d->lgt[i]) == 1) {
					memcpy( temp_mem, d->tab+i, d->lgt[i] * sizeof(int) );
					memcpy( d->tab+i, d->tab+j, d->lgt[j] * sizeof(int) );
					memcpy( d->tab+j, temp_mem, d->lgt[i] * sizeof(int) );
					temp_lgt = d->lgt[i];
					d->lgt[i] = d->lgt[j];
					d->lgt[j] = temp_lgt;
				}
			} 
		}

	}
}


int cmp_str(int *str1, int *str2, int n) {

	int i;
	for(i = 0; i < n; i++) {
		if(str1[i] > str2[i])
			return 1;
	}

	return 0;
}
